<template>
  <div class="app-container">
    <!-- <div class="header_title_box">
      <h2>入库单管理</h2>
    </div> -->
    <div class="mb10">
      <form-selections :is-active="isActive" :items="formItems" :query-param.sync="queryParam" display="block" @handleSearch="handleSearch" />
    </div>
    <div class="select_button_box">
      <div>
        <el-button size="small" type="primary" class="filter-item search" icon="el-icon-search" @click="handleSearch">
          搜索
        </el-button>
        <el-button size="small" icon="el-icon-refresh" @click="handleRefresh">重置</el-button>
      </div>
    </div>

    <!-- 入库订单类型 -->
    <el-tabs v-model="queryParam.source" type="card" class="margin-bottom-0" @tab-click="tabClick">
      <el-tab-pane label="采购商品入库" name="purchase">
        <!-- <div class="operation_button_box">
          <el-button v-action="'warehouseOrder@export'" size="middle" type="primary" :loading="exportLoading" @click="handleExport">导出</el-button>
        </div> -->
      </el-tab-pane>
      <el-tab-pane label="手工入库" name="manual">
        <!-- <div class="operation_button_box">
          <el-button v-action="'warehouseOrder@save'" size="middle" type="primary" icon="el-icon-circle-plus-outline" @click="toAddWarehouseOrder">创建入库单</el-button>
          <el-button v-action="'warehouseOrder@SubmitAudit'" size="middle" type="primary" @click="submitAudit">提交审核</el-button>
          <el-button v-action="'warehouseOrder@changeAuditStatus'" size="middle" type="primary" @click="showAuditDialog">审核</el-button>
          <el-button v-action="'warehouseOrder@inStock'" size="middle" type="primary" @click="enterWarehouse">确认入库</el-button>
          <el-button v-action="'warehouseOrder@batchDelete'" size="middle" type="danger" @click="dels(0)">批量删除</el-button>
          <el-button v-action="'warehouseOrder@export'" size="middle" type="primary" :loading="exportLoading" @click="handleExport">导出</el-button>
        </div> -->
      </el-tab-pane>
      <el-tab-pane label="退货入库" name="returned">
        <!-- <div class="operation_button_box">
          <el-button size="middle" type="primary" @click="enterWarehouse">确认入库</el-button>
          <el-button v-action="'warehouseOrder@export'" size="middle" type="primary" :loading="exportLoading" @click="handleExport">导出</el-button>
        </div> -->
      </el-tab-pane>
      <el-tab-pane label="调拨入库" name="allot">
        <!-- <div class="operation_button_box">
          <el-button size="middle" type="primary" @click="enterWarehouse">确认入库</el-button>
          <el-button v-action="'warehouseOrder@export'" size="middle" type="primary" :loading="exportLoading" @click="handleExport">导出</el-button>
        </div> -->
      </el-tab-pane>
      <el-tab-pane label="盘点入库" name="check">
        <!-- <div class="operation_button_box">
          <el-button size="middle" type="primary" @click="enterWarehouse">确认入库</el-button>
          <el-button v-action="'warehouseOrder@export'" size="middle" type="primary" :loading="exportLoading" @click="handleExport">导出</el-button>
        </div> -->
      </el-tab-pane>
      <el-tab-pane label="作废入库" name="void" />
    </el-tabs>
    <div class="select_flex">
      <div v-show="queryParam.source === 'purchase'" class="operation_button_box">
        <el-button v-action="'warehouseOrder@export'" size="small" type="primary" :loading="exportLoading" @click="handleExport">导出</el-button>
      </div>
      <div v-show="queryParam.source === 'manual'" class="operation_button_box">
        <el-button v-action="'warehouseOrder@save'" size="small" type="primary" icon="el-icon-circle-plus-outline" @click="toAddWarehouseOrder">创建入库单</el-button>
        <el-button v-action="'warehouseOrder@SubmitAudit'" size="small" type="primary" @click="submitAudit">提交审核</el-button>
        <el-button v-action="'warehouseOrder@changeAuditStatus'" size="small" type="primary" @click="showAuditDialog">审核</el-button>
        <el-button v-action="'warehouseOrder@inStock'" size="small" type="primary" @click="enterWarehouse">确认入库</el-button>
        <el-button v-action="'warehouseOrder@batchDelete'" size="small" type="danger" @click="dels(0)">批量删除</el-button>
        <el-button v-action="'warehouseOrder@export'" size="small" type="primary" :loading="exportLoading" @click="handleExport">导出</el-button>
      </div>
      <div v-show="queryParam.source !== 'manual' && queryParam.source !== 'purchase' && queryParam.source !== 'void'" class="operation_button_box">
        <el-button v-action="'warehouseOrder@inStock'" size="small" type="primary" @click="enterWarehouse">确认入库</el-button>
        <el-button v-action="'warehouseOrder@export'" size="small" type="primary" :loading="exportLoading" @click="handleExport">导出</el-button>
      </div>
    </div>
    <!-- 表格 -->
    <div v-loading="loading">
      <el-table :data="data" border fit :row-class-name="tableRowClassName" :max-height="screenHeigh" @selection-change="handleSelectMulti">
        <el-table-column key="selection" type="selection" width="51" align="center" />
        <el-table-column v-if="queryParam.source === 'manual'" key="opretion" label="操作" align="center" width="135" fixed>
          <template slot-scope="scope">
            <span v-if="scope.row.audit_status !== 2" v-action="'warehouseOrder@update'" class="edit_style" style="margin: 0;" @click="handleUpdate(scope.row)">编辑</span>
            <span v-if="scope.row.audit_status !== 2" v-action="'warehouseOrder@batchDelete'" class="delete_style" style="margin: 0;" @click="dels(scope.row.id)">删除</span>
          </template>
        </el-table-column>
        <el-table-column v-if="queryParam.source === 'manual'" key="code1" label="入库单号" align="center" width="203">
          <template slot-scope="scope">
            <code-item :code="scope.row.code" @click="showInfoDialog(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column v-else key="code2" label="入库单号" align="center" width="203">
          <template slot-scope="scope">
            <code-item :code="scope.row.code" @click="showInfoDialog(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column key="virtual_warehouse" label="入库虚拟仓" prop="virtual_warehouse" align="center" min-width="222" />
        <el-table-column key="entity_warehouse" label="入库实体仓" prop="entity_warehouse" align="center" width="222" />
        <el-table-column align="center" label="系统SKU|商品名称|数量" width="400px" show-overflow-tooltip>
          <template slot-scope="scope">
            <div v-for="(item, index) in scope.row.products" :key="index">
              <el-divider v-if="index !==0" class="line_style" />
              <span>{{ item.goods_code }}<b>|</b>{{ item.goods_name }}<b>|</b>{{ item.number }} </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column v-if="queryParam.source !== 'manual'" align="center" label="配件SKU|配件名称|数量" width="300px" show-overflow-tooltip>
          <template slot-scope="scope">
            <div v-for="(item, index) in scope.row.parts" :key="index">
              <el-divider v-if="index !==0" class="line_style" />
              <span>{{ item.goods_code }}<b>|</b>{{ item.goods_name }}<b>|</b>{{ item.number }} </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column v-if="queryParam.source === 'manual'" key="audit_by_name" label="审核人" prop="audit_by_name" align="center" width="222">
          <template slot-scope="scope">
            <app-text :text="scope.row.audit_by_name" />
          </template>
        </el-table-column>
        <el-table-column v-if="queryParam.source === 'manual'" key="audit_time" label="审核时间" prop="audit_time" align="center" width="222">
          <template slot-scope="scope">
            <app-text :text="scope.row.audit_time" />
          </template>
        </el-table-column>
        <el-table-column v-if="queryParam.source === 'manual'" key="audit_status" label="审核状态" prop="audit_status" align="center" width="222">
          <template slot-scope="scope">
            <span>{{ statusMap[scope.row.audit_status] }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="queryParam.source === 'manual'" key="audit_notes" label="审核原因" prop="audit_status" align="center" width="222">
          <template slot-scope="scope">
            <span>{{ scope.row.audit_notes || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="queryParam.source !== 'purchase'" key="warehousing_status_text" label="入库状态" prop="warehousing_status_text" align="center" width="222" />
        <el-table-column key="warehousing_time" label="入库时间" prop="warehousing_time" align="center" width="200" />
        <el-table-column v-if="queryParam.source === 'purchase'" key="cabinet_no" label="柜号" prop="cabinet_no" align="center" width="200" />
        <el-table-column key="created_by_name" label="创建人" prop="created_by_name" align="center" width="112" />
        <el-table-column key="created_at" label="创建时间" prop="created_at" align="center" width="174" />
        <el-table-column key="updated_by_name" label="修改人" prop="updated_by_name" align="center" width="112" />
        <el-table-column key="updated_at" label="修改时间" prop="updated_at" align="center" width="174" />
      </el-table>
      <el-pagination v-if="paginate.total > 0" class="pagination_box" background :current-page="paginate.current" :page-sizes="[10, 20, 30, 40]" layout="total, sizes, prev, pager, next, jumper" :total="paginate.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
    <audit-dialog ref="auditDialog" :base-fields="baseFields" :number-desc="numberDesc" :change-audit-url="changeAuditUrl" :info-url="infoUrl" @submit="auditHandler" />
    <warehouse-order-info-dialog ref="infoDialog" :base-fields="baseFields" :number-desc="numberDesc" />
    <!--下载字段选择-->
    <DownModul :url="exportUrl" :search-param="downLoadParams" :form-visible-down.sync="formVisibleDown" titel="入库单导出字段选择" :options-modul="optionsModul" />
  </div>
</template>

<script>
import formOperate from '../../../layout/mixin/formOperate'
import { action } from '@/directive/permission/index.js' // 权限判断指令
import auditDialog from '../components/auditDialog'
import warehouseOrderInfoDialog from '../components/warehouseOrderInfoDialog'
import codeItem from '../../../components/base/code'
import appText from '../../../components/appText/index'
// import productList from '../../../components/productList/index'
import cacheList from '../../../layout/mixin/cacheList'
import DownModul from '@/components/DownModul/index.vue'
// import Tempalant from '@/views/tempalant.vue'
export default {
  name: 'WarehouseOrder', // 入库单
  components: {
    auditDialog,
    warehouseOrderInfoDialog,
    codeItem,
    appText,
    // productList,
    DownModul
    // Tempalant
  },
  directives: {
    action
  },
  mixins: [formOperate, cacheList],
  data() {
    return {
      otherHeight: 395,
      componentName: 'WarehouseOrder', // 入库单
      statusList: [
        {
          id: 0,
          name: '待提交'
        },
        {
          id: 1,
          name: '待审核'
        },
        {
          id: 2,
          name: '审核通过'
        },
        {
          id: -1,
          name: '审核驳回'
        }
      ], // 审核状态list
      statusMap: {
        0: '待提交',
        1: '待审核',
        2: '审核通过',
        '-1': '审核驳回'
      },
      formItem1: [
        {
          label: '入库单号',
          key: 'code',
          type: 'input',
          placeholder: '请输入入库单号'
        },
        {
          label: '柜号',
          key: 'cabinet_no',
          type: 'input',
          placeholder: '请输入柜号'
        },
        {
          label: '仓库名称',
          key: 'warehouse_name',
          type: 'input',
          placeholder: '请输入仓库名称'
        },
        {
          label: '商品SKU',
          key: 'goods_code',
          type: 'input',
          placeholder: '请输入商品SKU'
        },
        {
          label: '审核状态',
          key: 'audit_status',
          type: 'select',
          filterable: true,
          placeholder: '请选择审核状态',
          options: [
            {
              value: 0,
              label: '待提交'
            },
            {
              value: 1,
              label: '待审核'
            },
            {
              value: 2,
              label: '审核通过'
            },
            {
              value: -1,
              label: '审核驳回'
            }
          ]
        },
        {
          label: '创建时间',
          key: 'dateCreat',
          type: '',
          valueFormat: 'yyyy-MM-dd HH:mm:ss',
          placeholder: '请选择时间范围'
          //   wrap: true
        }
      ],
      formItem2: [
        {
          label: '入库单号',
          key: 'code',
          type: 'input',
          placeholder: '请输入入库单号'
        },
        {
          label: '仓库名称',
          key: 'warehouse_name',
          type: 'input',
          placeholder: '请输入仓库名称'
        },
        {
          label: '商品SKU',
          key: 'goods_code',
          type: 'input',
          placeholder: '请输入商品SKU'
        },
        {
          label: '审核状态',
          key: 'audit_status',
          type: 'select',
          filterable: true,
          placeholder: '请选择审核状态',
          options: [
            {
              value: 0,
              label: '待提交'
            },
            {
              value: 1,
              label: '待审核'
            },
            {
              value: 2,
              label: '审核通过'
            },
            {
              value: -1,
              label: '审核驳回'
            }
          ]
        },
        {
          label: '创建时间',
          key: 'dateCreat',
          type: '',
          valueFormat: 'yyyy-MM-dd HH:mm:ss',
          placeholder: '请选择时间范围'
          //   wrap: true
        }
      ],
      formItems: [
        {
          label: '入库单号',
          key: 'code',
          type: 'input',
          placeholder: '请输入入库单号'
        },
        {
          label: '柜号',
          key: 'cabinet_no',
          type: 'input',
          placeholder: '请输入柜号'
        },
        {
          label: '仓库名称',
          key: 'warehouse_name',
          type: 'input',
          placeholder: '请输入仓库名称'
        },
        {
          label: '商品SKU',
          key: 'goods_code',
          type: 'input',
          placeholder: '请输入商品SKU'
        },
        {
          label: '审核状态',
          key: 'audit_status',
          type: 'select',
          filterable: true,
          placeholder: '请选择审核状态',
          options: [
            {
              value: 0,
              label: '待提交'
            },
            {
              value: 1,
              label: '待审核'
            },
            {
              value: 2,
              label: '审核通过'
            },
            {
              value: -1,
              label: '审核驳回'
            }
          ]
        },
        {
          label: '创建时间',
          key: 'dateCreat',
          type: '',
          valueFormat: 'yyyy-MM-dd HH:mm:ss',
          placeholder: '请选择时间范围'
          //   wrap: true
        }
      ],
      url: '/warehouse-order',
      queryParam: {
        code: '', // 入库单号
        cabinet_no: '', // 柜号
        goods_code: '',
        warehouse_name: '',
        audit_status: '', // 入库单审核状态
        source: 'purchase' // 入库单类型
      }, // 搜索参数
      defaultQueryParam: ['source'], // 搜索参数不清空列表
      // 入库单类型 map
      sourceMap: {
        purchase: '采购商品入库',
        manual: '手工入库',
        returned: '退货入库',
        allot: '调拨入库',
        check: '盘点入库'
      },
      baseFields: [
        {
          id: 1,
          label: '入库单号',
          prop: 'code'
        },
        {
          id: 2,
          label: '入库实体仓',
          prop: 'entity_warehouse'
        },
        {
          id: 3,
          label: '入库虚拟仓',
          prop: 'virtual_warehouse'
        },
        {
          id: 4,
          label: '入库原因',
          prop: 'notes'
        }
      ],
      numberDesc: {
        label: '入库数量',
        prop: 'number'
      },
      changeAuditUrl: '/warehouse-order/change-audit-status',
      infoUrl: '/warehouse-order',
      exportUrl: '/warehouse-order-export',
      cachePaths: [
        '/storage/warehouseOrder/add'
      ],
      optionsModul: [
        {
          key: 'code',
          label: '入库单号'
        },
        {
          key: 'entity_warehouse',
          label: '入库实体仓'
        },
        {
          key: 'virtual_warehouse',
          label: '入库虚拟仓'
        },
        {
          key: 'warehousing_status_text',
          label: '入库状态'
        },
        {
          key: 'warehousing_time',
          label: '入库时间'
        },
        {
          key: 'goods_name',
          label: '商品名称'
        },
        {
          key: 'goods_code',
          label: '商品SKU'
        },
        {
          key: 'number',
          label: '商品数量'
        },
        {
          key: 'created_by_name',
          label: '创建人'
        },
        {
          key: 'created_at',
          label: '创建时间'
        }
      ]
    }
  },
  activated() {
    this.getList()
  },
  methods: {
    beforeSearch() {
      const vm = this
      const { dateCreat } = vm.queryParam
      if (dateCreat && dateCreat.length > 0) {
        vm.queryParam.start_at_creat = vm.queryParam.dateCreat[0]
        vm.queryParam.end_at_creat = vm.queryParam.dateCreat[1]
      } else {
        vm.queryParam.start_at_creat = ''
        vm.queryParam.end_at_creat = ''
      }
    },
    // 导出
    handleExport() {
      const vm = this
      // const { code, audit_status, source } = vm.queryParam
      // const params = { code, audit_status, source }
      vm.downLoadParams = vm.queryParam
      vm.formVisibleDown = true
      // vm.handleExportxlsx(vm.exportUrl, params)
    },
    // tab 点击
    tabClick() {
      const vm = this
      vm.data = []
      if (this.queryParam.source === 'purchase') {
        this.formItems = this.formItem1
      } else {
        this.formItems = this.formItem2
      }
      vm.handleSearch()
    },
    /**
     * 去添加入库单
     * */
    toAddWarehouseOrder() {
      const vm = this
      window.localStorage.removeItem('warehouseOrder')
      vm.$router.push({ path: '/storage/warehouseOrder/add' })
    },
    filterData(data) {
      return data.map(e => {
        e['codes'] = e.products.map(pro => pro.goods_code)
        e['names'] = e.products.map(pro => pro.goods_name)
        return e
      })
    },
    // 批量删除
    dels(id) {
      const vm = this
      let ids = []
      if (id) {
        ids.push(id)
      } else {
        ids = vm.selectedIds
      }
      vm.$confirm(`确定${id ? '' : '批量'}删除吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        vm.$http.post('/warehouse-order/batch-delete', { ids }).then((res) => {
          vm.$message.success('删除成功')
          vm.getList()
        })
      })
    },
    // 编辑入库单
    handleUpdate(row) {
      const vm = this
      if (row.audit_status === 2) {
        vm.$message.error('入库单已审核通过,不可编辑')
        return
      }
      window.localStorage.removeItem('warehouseOrder')
      vm.$router.push({
        path: `/storage/warehouseOrder/add/${row.id}`,
        query: { title: '编辑入库单' }
      })
    },
    // 提交审核
    submitAudit() {
      const vm = this
      if (vm.selectedIds.length <= 0) {
        vm.$message.error('请至少选择一条数据')
        return
      }
      // 判断列表是否都是 待提交状态
      const isEveryToSubmit = vm.data
        .filter((e) => vm.selectedIds.includes(e.id))
        .every((e) => e.audit_status === 0 || e.audit_status === -1)
      if (isEveryToSubmit) {
        vm.$confirm(`确定提交审核吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          vm.$http
            .post('/warehouse-order/submit-audit', { ids: vm.selectedIds })
            .then((res) => {
              vm.$message.success('提交审核成功')
              vm.getList()
            })
        })
      } else {
        vm.$message.error('选择数据须都是待提交或审核驳回状态')
      }
    },
    // 审核
    showAuditDialog() {
      const vm = this
      if (vm.selectedIds.length <= 0) {
        vm.$message.error('请至少选择一条数据')
        return
      }
      if (vm.selectedIds.length > 1) {
        vm.$message.error('请至多选择一条数据')
        return
      }
      const firstId = vm.selectedIds[0]
      const first = vm.data.find((e) => e.id === firstId)
      // 是否都是待审核状态
      if (first.audit_status !== 1) {
        vm.$message.error('选择数据必须是待审核状态')
        return
      }
      vm.$refs['auditDialog'].show({
        id: firstId,
        auditStatus: [
          { label: 2, name: '审核通过' },
          { label: -1, name: '审核驳回' }
        ]
      })
    },
    // 审核成功之后handler
    auditHandler() {
      const vm = this
      vm.getList()
    },
    // 确认出库
    enterWarehouse() {
      const vm = this
      if (vm.selectedIds.length <= 0) {
        vm.$message.error('请至少选择一条数据')
        return
      }
      if (vm.selectedIds.length > 1) {
        vm.$message.error('请至多选择一条数据')
        return
      }
      vm.$confirm(`确定提交入库吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const id = vm.selectedIds[0]
        vm.$http.put(`/warehouse-order/in-stock/${id}`).then(() => {
          vm.$message.success('入库成功')
          vm.getList()
        })
      })
    },
    // 显示详情dialog
    showInfoDialog(infodata) {
      const vm = this
      const info = {}
      vm.$refs.infoDialog.show({
        info,
        showParts: ['purchase', 'allot', 'check'].indexOf(vm.queryParam.source) > -1,
        id: infodata.id,
        type: 'warehouse'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.margin-bottom-0.el-tabs--card ::v-deep .el-tabs__header {
  margin-bottom: 0;
}
.operation_button_box ::v-deep .el-button + .el-button {
  margin-left: 14px;
}
</style>
